package com.kfm.hotel.controller;

import com.anji.captcha.util.AESUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.kfm.hotel.domain.SysUser;
import com.kfm.hotel.interceptor.RememberMeInterceptor;
import com.kfm.hotel.service.MailService;
import com.kfm.hotel.service.SysUserService;
import com.kfm.hotel.util.Constant;
import com.kfm.hotel.util.MD5Util;
import com.kfm.hotel.util.R;
import com.mysql.cj.Session;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.MessagingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class LoginController {
    //登录成功后进行共享业务
    @Autowired
    private SysUserService service;
    //后台接受到了email文件
    @Autowired
    private MailService mailService;
    //注入RememberMeInterceptor接口
    //前端使用get请求:响应页面使用ModelAndView
    //CookieValue(value = "username",required =false):从cookie中获取登录信息，不登录取不到
    //value ="remember_me_user":拿到remember_me_user

    @GetMapping({"/","/login"})

    public ModelAndView login(@CookieValue(value =Constant.REMEMBER_ME_COOKIE_NAME,required =false) String user,
                              HttpSession session) throws Exception {
        ModelAndView modelAndView = new ModelAndView("login");
        return modelAndView;
    }
    //邮箱
    @GetMapping({"/email"})
    public ModelAndView email(){
        ModelAndView view = new ModelAndView("email");
        return view;
    }
    @PostMapping({"/email/login"})
    public R sendEmail(String email, HttpSession session) throws MessagingException {
        // TODO 根据邮箱查询用户, 如果用户存在，发送邮件
        int code = mailService.loginCodeEmail(email);
        // 保存验证码到 session
        session.setAttribute(Constant.LOGIN_CODE, code);
        return R.ok("登录成功","/index");
        //return R.ok(email);
    }



    //后端使用post接收对象,json对象,响应数据使用R
    @PostMapping({"/login"})
    public R login(@RequestBody SysUser user, HttpServletResponse response, HttpSession session) throws Exception {
        //AES解密,原始的密码
        String str = AESUtil.aesDecrypt(user.getPassword(), user.getKey());
        user.setPassword(str);
        //根据传入的用户名和密码进行查询用户信息
        SysUser one = service.login(user);
        if(one!=null){
            if(user.getRememberMe()!=null&&user.getRememberMe()) {
                //"记住我功能“
                extracted(user, response, str);
            }
                //登录成功，session中取值
                session.setAttribute(Constant.LOGIN_USER, one);

            return R.ok("登录成功","/index");
        }else{
            return R.fail("用户名或密码错误！");
        }
    }

    private static void extracted(SysUser user, HttpServletResponse response, String str) throws Exception {
        if(user.getRememberMe()!=null&& user.getRememberMe()){
            //对用户名和密码进行加密
            //加密后的密码
            String aesEncrypt = AESUtil.aesEncrypt(user.getUsername(), Constant.REMEMBER_ME_AES_KEY);
            String enPass=AESUtil.aesEncrypt(str,Constant.REMEMBER_ME_AES_KEY);
            //用户名加密

            //将用户名和密码用“--”连接
            String value=aesEncrypt+Constant.REMEMBER_ME_COOKIE_SPLIT_CHAR+enPass;
            //1.创建cookie存用户名
            Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, value);
            //2.创建有效期
            cookie.setMaxAge(60*60*24*7);
            //3.设置cookie的作用域为根目录
            cookie.setPath("/");
            //4.将cookie添加到响应头中去
            response.addCookie(cookie);
        }
    }


    //响应到index页面,使用视图
    @GetMapping("/index")
    public ModelAndView index(@SessionAttribute (value =Constant.LOGIN_USER) SysUser user){
        ModelAndView andView = new ModelAndView("index");
        andView.addObject("name",user.getName());
        return andView;
    }
    //响应到welcome页面，使用视图
    @GetMapping("/welcome")
    public ModelAndView welcome(){
        ModelAndView welcome = new ModelAndView("welcome");
        return welcome;
    }

    /**
     * 注销操作
     */
    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session,HttpServletResponse response){
        //退出登录，删除session中的用户信息
        session.removeAttribute(Constant.LOGIN_USER);
        //退出登录，删除cookie
        Cookie cookie = new Cookie(Constant.REMEMBER_ME_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new ModelAndView("redirect:/login");
    }
}
